<template>
  <div class="putstore">
        <div class="top-add">
            <div style="width:70%">
              <el-page-header @back="backPutStore" content="新增入库单"></el-page-header>
            </div>
            <div>
                 <el-button size="mini" v-if="!isReturnStore" type="primary" @click="selectProd">选择装备</el-button>
                 <el-button size="mini" v-else type="primary" @click="selectBorrowOrder">选择借用出库单</el-button>
                <el-button size="mini" type="primary" @click="submitPutstore">保存</el-button>
                <el-button size="mini" v-if="!isReturnStore" type="primary" @click="inExcelFile">导入</el-button>
                <el-button size="mini" v-if="!isReturnStore" type="primary" @click="downloadExecl">下载批量模板</el-button>
                <!-- <el-button size="mini" type="primary" @click="backPutStore">取消</el-button> -->
            </div> 

            <input type="file" @change="importFile(this)" id="imFile" style="display: none"
              accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/>
            
        </div>
      <el-row :gutter="16" style="line-height:40px;margin-top:-20px;margin-bottom:20px">
        <el-col :span="4">
          <div class="">
            <label for="">入库单号</label>
            <el-input v-model="put_num" size="small" disabled placeholder="自动生成" style="width:80%"></el-input>
          </div>
        </el-col>

         <el-col :span="4">
          <div>
            <label for="">入库类型</label>
            <div class="main-content">
              <el-select v-model="put_type" placeholder="请选择" style="width:80%"  size="small">
                <el-option
                  v-for="item in putTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
          </div>
        </el-col>

        <el-col :span="4">
          <div class="">
            <label for="">入库日期</label>
            <el-date-picker size="small" type="date" style="width:80%" placeholder="选择日期" v-model="put_date"></el-date-picker>
          </div> 
        </el-col>

        <!-- <el-col :span="4">
          <div class="">
            <label for="">供应商名称</label>
            <el-input v-model="supplier_name" size="small" style="width:80%"></el-input>
          </div> 
        </el-col> -->

        <el-col :span="4">
          <div class="">
            <label for="">制单人</label>
            <el-input v-model="put_person" size="small" style="width:80%"></el-input>
          </div> 
        </el-col>

        <el-col :span="4">
            <label for="">备注</label>
            <el-input v-model="put_remark" size="small" placeholder="" style="width:90%"></el-input>
        </el-col>

      </el-row>

      <el-row>
        <el-col :span="24">
          <el-table :data="putSelectProd" border style="width: 100%">
            <!-- <el-table-column type="selection" width="40"></el-table-column> -->
            <!-- <el-table-column label="图片" width="60">
              <template slot-scope="scope">
                <div>
                  <img style="width:40px;height:40px;" :src="scope.row.prodImg" alt="">
                </div>
              </template>
            </el-table-column> -->
            <el-table-column prop="categoryTwoName" label="装备细类"></el-table-column>
            
            <el-table-column prop="prodName" label="装备名称" width="120">
              <template slot-scope="scope">
                <div>
                  <el-autocomplete
                    size="mini"
                    popper-class="my-autocomplete"
                    v-model="scope.row.prodName"
                    :fetch-suggestions="querySearch"
                    placeholder="请输入名称"
                    @focus="changeProd(scope.row)"
                    @select="handleSelect">
                    <template slot-scope="{ item }">
                      <div class="name">{{ item.prodName }}</div>
                    </template>
                  </el-autocomplete>

                </div>
              </template>
            </el-table-column>

            <!-- <el-table-column prop="prodCode" label="装备编号">
              <template slot-scope="scope">
                <div>
                  <el-input size="mini" v-model="scope.row.prodCode"></el-input>
                </div>
              </template>
            </el-table-column> -->

            <el-table-column label="规格">
              <template slot-scope="scope">
                <div>
                  <el-input size="mini" v-model="scope.row.prodSpecial"></el-input>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="批次" width="120">
              <template slot-scope="scope">
                <div>
                  <el-input size="mini" v-model="scope.row.prodBatch" placeholder="批次号"></el-input>
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="prodNum" label="数量"  width="80">
              <template slot-scope="scope">
                <div>
                  <el-input size="mini" v-model="scope.row.prodNum"></el-input>
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="emit" label="单位" width="80">
              <template slot-scope="scope">
                <div>
                  <el-input size="mini" v-model="scope.row.emit"></el-input>
                </div>
              </template>
            </el-table-column>

            <!-- <el-table-column prop="prodPrice" label="价格">
              <template slot-scope="scope">
                <div>
                  <el-input size="mini" v-model="scope.row.prodPrice"></el-input>
                </div>
              </template>
            </el-table-column> -->

            <el-table-column prop="supplierName" label="供应商名称" width="130">
              <template slot-scope="scope">
                <div>
                  <el-select v-model="scope.row.supplierId" placeholder="请选择" size="mini">
                    <el-option
                      v-for="item in supplierlist"
                      :key="item.supplierId"
                      :label="item.supplierName"
                      :value="item.supplierId">
                    </el-option>
                  </el-select>
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="prodArea" label="库区" width="130">
              <template slot-scope="scope">
                <div>
                  <el-select v-model="scope.row.prodArea" placeholder="请选择" size="mini" @change="choseArea">
                    <el-option
                      v-for="item in arealist"
                      :key="item.areaId"
                      :label="item.areaName"
                      :value="item.areaId">
                    </el-option>
                  </el-select>
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="prodDepart" label="库位" width="120">
              <template slot-scope="scope">
                <div>
                  <el-select v-model="scope.row.prodDepart" placeholder="请选择" size="mini">
                    <el-option
                      v-for="item in departlist"
                      :key="item.departmentId"
                      :label="item.departmentCode"
                      :value="item.departmentId">
                    </el-option>
                  </el-select>
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="prodDate" label="到期时间" width="144">
              <template slot-scope="scope">
                <div>
                  <el-date-picker  style="width:128px" size="mini" type="date" placeholder="选择日期" v-model="scope.row.prodDate"></el-date-picker>
                </div>
              </template>   
            </el-table-column>
        
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" icon="el-icon-delete" @click="delSelectProd(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>

      

      <div class="autospace"></div>

      <selectcategory :selectprodDialog.sync="selectprodDialog"></selectcategory>
      <selectReturnOrder :returnOrderDialog.sync="returnOrderDialog"></selectReturnOrder>
      <excel :trueInExcel.sync='trueInExcel' :inexeclData.sync="putSelectProd" :inexecl="inexecl" style="display:none"></excel>
  </div>
</template>

<script>
import { FindStoreArea, FindAreaDepart} from '@/api/store.js';
import { GetProdsByCate, SearchProdsByCate, GetSuppier } from '@/api/prod';
import { PutstoreInfo, FindPutOrderById, UpdatePutOrder, getPutExeclTemp, PutstoreExcel } from '@/api/putstore.js';
import { getStore } from '@/utils/app.js';
import selectcategory from './selectcategory';
import selectReturnOrder from '@/views/putstore/selectReturnOrder';
import excel from '../test/excel';
export default {
  name: 'putstore',
  components: {
    selectcategory,
    excel,
    selectReturnOrder
  },
  data() {
    return {
        selectprodDialog: false, // 打开选择商品弹框
        is_search: false,
        put_num: '',
        put_type: 1,
        put_date: '',
        put_person: '',
        put_remark: '',
        putId: null, // 修改入库单时的id
        checkProdsByCate: [],
        restaurants: [],
        arealist: [],
        departlist: [],
        supplierlist: [],
        checkprodName: '',
        putSelectProd: [],
        restaurants: [],   // 商品名称下拉选择
        putTypeList: [
            { id:1, name: '采购入库'},
            { id:2, name: '归还入库'},
            { id:3, name: '退入库'},
            { id:4, name: '调拨入库'},
            { id:5, name: '其他入库'},
        ],
        isReturnStore: false,   // 是否是归还入库
        returnOrderDialog: false,
        trueInExcel: false,
        inexecl: ['putCode','categoryName','categoryTwoName','prodName','prodNum','emit','prodPrice','prodSpecial','supplierName']
    }
    
  },
  computed: {
    storeid() {
      return this.$store.state.store.store_id || getStore();
    },
    main_store() {
      return this.$store.state.store.main_store;
    },
    getSelectprod() {
      return this.$store.state.ware.selectProds;
    }
  },
  watch: {
    selectprodDialog(newVal) {
      if (!newVal) {
        let newArr = this.putSelectProd.concat(this.getSelectprod);
        this.putSelectProd = JSON.parse(JSON.stringify(newArr));
        for( let n = 0; n < this.putSelectProd.length; n++) {        
          this.putSelectProd[n].edit_id = n + 1;
          GetProdsByCate(this.putSelectProd[n].categoryTwoId).then( res => {
             this.$set(this.putSelectProd[n],'categoryTwos',res.data)
          })  
        }
      }
    },
    // 监控入库类型是否是归还入库
    put_type(newVal) {
      if (newVal == 2) {
        this.isReturnStore = true
      } else {
        this.isReturnStore = false
      }
    }
  },
  mounted() {
    this.imFile = document.getElementById('imFile')
    this.getStoreArea();
    this.getSuppliers()
    // 修改入库单时获取数据
    this.putId = this.$route.query.putid;
    if (this.putId) {
      FindPutOrderById(this.putId).then( res => {
        let orderDetail = res.data[0];
        orderDetail.putDate = this.formatDate(orderDetail.putDate);
        this.put_num = orderDetail.orderNum;
        this.put_type = orderDetail.putTypeid;
        this.put_date = orderDetail.putDate;
        this.put_person = orderDetail.putPerson;
        this.put_remark = orderDetail.putRemark;
        this.putSelectProd = orderDetail.putProds;
        // 判断库区是否有值，有值加载库位
        this.putSelectProd.forEach( e => {
          if (e.prodArea) {
            this.choseArea(e.prodArea);
          }
        })
        for( let n = 0; n < this.putSelectProd.length; n++) {        
          this.putSelectProd[n].edit_id = n + 1;
        }
      })
    }  
  },
  methods:{
    downloadExecl() {
      getPutExeclTemp().then( res => {
        let execlurl = res.data.data;
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = execlurl;
        document.body.appendChild(link);
        link.click();
      })
    },
    changeProd(item) {    
      this.restaurants = item.categoryTwos;
    },
    querySearch(queryString, cb) {
        var restaurants = this.restaurants;
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
    },

    createFilter(queryString) {
      return (restaurant) => {
          return (restaurant.prodName.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(item) {
      console.log(item);
      this.putSelectProd.forEach( e => {
        e.categoryTwos.forEach(val => {
          if (val.prodName == item.prodName ) {
            e.prodName = item.prodName;
            e.prodImg = val.prodImg;
            e.prodSpecial = val.prodSpecial;
            e.emit = val.emit;
            e.supplierId = val.supplierId;    
            e.supplierName = val.supplierName;
            e.prodCode = val.prodCode;
          }
        })
      })
    },
    // 获取供应商
    getSuppliers() {
      GetSuppier().then( res => {
        this.supplierlist = res.data;
      })
    },
    // 获取页面仓库和库区
    getStoreArea() {
      FindStoreArea(this.storeid).then( res => {
          this.arealist = res.data;
      })
    },
    // 选择库区显示库位
    choseArea(val) {
      // 根据库区id加载库位数据
      FindAreaDepart(val).then( res => {
        this.departlist = res.data;
      })
    },
    // 导入
    inExcelFile() {
      // this.trueInExcel = true;
      this.imFile.click()
    },
    importFile: function () { // 导入excel
      let obj = this.imFile
      var f = obj.files[0]   // 获取第一个文件

      var formdata = new FormData()
      formdata.append('file', f)
      PutstoreExcel(formdata).then(res => {
        if (res.data.code == 1 ) {
          this.$message({
            message: '导入成功',
            type: 'success'
          })
          setTimeout(() => {
            this.$router.push('/putstore')
          }, 1000)
        } else {
          this.$message({
            message: res.data.msg,
            type: 'success'
          })
        }
      })
    },
    // 去选择商品
    selectProd() {
      this.selectprodDialog = true;
    },
    // 归还入库时选择借用出库单
    selectBorrowOrder() {
      this.returnOrderDialog = true;
    },
    backPutStore() {
        this.$router.push('/putstore')
    },
    delSelectProd(el) {
      this.putSelectProd = this.putSelectProd.filter( e => e.edit_id != el.edit_id);
    },
    // 保存入库信息
    submitPutstore() {
      if (this.putSelectProd.length == 0) {
        this.$message({
          message: '请选择入库装备',
          type: 'warning'
        })
      } else {
        this.putSelectProd.forEach( e => {
          if(e.prodDate) {
            return e.prodDate = this.formatDate(e.prodDate)
          }
        })
        this.put_date = this.formatDate(this.put_date);
        if (this.putId) {
          // 存在即修改
          let reqData = {
              orderNum: this.put_num,
              putId: this.putId,
              putTypeid: this.put_type,
              putDate: this.put_date,
              putPerson: this.put_person,
              putRemark: this.put_remark,
              putProds: this.putSelectProd,
          }
          // console.log(reqData)
          UpdatePutOrder(reqData).then( res => {
            this.$message({
              message: res.data.msg,
              type: 'success'
            })
            setTimeout(() => {
              this.$router.push('/putstore')
            }, 1000)
          }).catch( error => console.log(error))
        } else {
          // 不存在就新增
          let reqData = {
              orderNum: this.put_num,
              putTypeid: this.put_type,
              putDate: this.put_date,
              putPerson: this.put_person,
              putRemark: this.put_remark,
              putProds: this.putSelectProd,
          }
          // console.log(reqData)
          PutstoreInfo(reqData).then( res => {
            this.$message({
              message: res.data.msg,
              type: 'success'
            })
            setTimeout(() => {
              this.$router.push('/putstore')
            }, 1000)
          }).catch( error => console.log(error))
        }
      }
    }
  },


}
</script>

<style lang="scss" scoped>
@import '../../styles/config.scss';

  .label-wrap {
    &.category { @include labelwrap(left,100,40); }
    &.date {
      @include labelwrap(center,50,40); }
    &.keyword { @include labelwrap(right,110,40); }
  }
  .autospace {
    height: 30px;
  }
  
  .top-add {
    width: 100%;
    height: 40px;
    margin-bottom: 20px;
    // font-weight: 700;
    border-bottom: 1px solid #f1f1f1;
    display: flex;
  }

  .my-autocomplete {
    li {
      line-height: normal;
      padding: 7px;

    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .addr {
      color: #ddd;
    }
  }
}
</style>
  
